from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse
from . models import *
from captcha.image import ImageCaptcha
import re,redis,random,string,jwt
# Create your views here.
# 校验用户名
class UserView(APIView):
    def get(self,request,user):
        if not re.findall(r'[a-zA-Z]\w{4,14}$',user):
            return Response({'code':400,'msg':'用户名格式不正确'})
        if User.objects.filter(username=user).count()>0:
            return Response({'code':401,'msg':'用户名已经存在'})
        return Response({'code':200,'msg':'用户名校验已通过'})

# 校验手机号
class Mobile(APIView):
    def get(self,request,phone):
        if not re.findall(r'^1[3-9]\d{9}$',phone):
            return Response({'code': 400, 'msg': '手机号格式不正确'})
        if User.objects.filter(phone=phone).count()>0:
            return Response({'code': 401, 'msg': '手机号已存在'})
        return Response({'code': 200, 'msg': '手机号校验已通过'})

# 生成校验短信验证码
class SmsCodeView(APIView):
    def get(self,request,phone):
        if not re.findall(r'^1[3-9]\d{9}$',phone):
            return Response({'code':400,'msg':'手机号格式不正确'})
        sms_code = random.randint(100000,999999)
        r = redis.Redis(host='localhost',port=6379,db=5)
        r.set(phone,sms_code, ex=120)
        r.close()
        return Response({'code':200,'msg':'短信验证码生成成功','sms_code':sms_code})

    def post(self,request,phone):
        if not re.findall(r'^1[3-9]\d{9}$',phone):
            return Response({'code':400,'msg':'手机号格式不正确'})
        codel = request.data.get('sms_code')
        r = redis.Redis(host='localhost',port=6379,db=5)
        code2 = r.get(phone)
        r.close()
        if code2:
            code2 = code2.decode()
        else:
            return Response({'code': 400, 'msg': '验证码失效'})
        if str(code2) != str(codel):
            return Response({'code': 401, 'msg': '验证码错误'})
        else:
            return Response({'code': 200, 'msg': '验证码正确'})

# 生成校验图形验证码
class ImgCode(APIView):
    def get(self,request,uuid):
        img_code = ''.join(random.sample(string.ascii_letters+string.digits,4))
        r = redis.Redis(host='localhost',port=6379,db=5)
        r.set(uuid,img_code,ex=120)
        r.close()
        cap = ImageCaptcha()
        img = cap.generate(img_code)
        return HttpResponse(img,content_type='image/png')

    def post(self,request,uuid):
        code1 = request.data.get('imgcode')
        r = redis.Redis(host='localhost', port=6379,db=5)
        code2 = r.get(uuid)
        r.close()
        if code2:
            code2 = code2.decode()
        else:
            return Response({'code':200,'msg':'图形验证码验证过期'})
        if code1.lower() == code2.lower():
            return Response({'code':200,'msg':'图片验证码验证成功'})
        else:
            return Response({'code':401,'msg':'图片验证码错误'})

# 注册功能
class Regster(APIView):
    def post(self,request,):
        user=request.data.get('user')
        phone=request.data.get('phone')
        pwd=request.data.get('pwd')
        print(pwd)

        if not all([user,phone,pwd]):
            return Response({'code':400,'msg':'字段不完整'})
        User.objects.create(user=user,password=pwd,phone=phone)
        return Response({'code':200,'msg':'注册成功，即将登录'})


from project1.settings import SECRET_KEY
def get_jwt(user):
    paylocd = {
        'id':user.id,
        'user':user.user
    }
    token = jwt.encode(payload=paylocd,key=SECRET_KEY,algorithm='HS256')
    return token
# 登录功能
class Login(APIView):
    def post(self,request):
        user = request.data.get('user')
        password = request.data.get('password')
        try:
            user=User.objects.get(user=user)
        except Exception as e:
            print(e)
            return Response({'code':400,'msg':'用户不存在'})
        if password != user.password:
            return Response({'code':401,'msg':'密码不正确'})
        token = get_jwt(user)
        return Response({
            'code':200,
            'msg':'登陆成功',
            'token':token,
            'user':{
                'id':user.id,
                'user':user.user
            }
        })

